// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// P [author] rhyme_lph
// z [email]  rhymelph@gmail.com
// O [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/setting_template_entity.dart';
import 'package:finance_app/src/http_service/http_preference_service.dart';
import 'package:finance_app/src/http_service/http_setting_service.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/form_utils.dart';

class TemplateStyleProvider extends BaseProvider<List<SettingTemplateEntity>> {
  List<String> templateList = [
    'Quotation',
    'Invoice',
    'Purchase Order',
    'Delivery Order',
    'Credit Note',
  ];

  String currentType = 'Quotation';

  @override
  Future get dataFuture => HttpSettingService.getSettingTemplates();

  void onChangeTemplate(String value) {
    currentType = value;
    update();
  }

  void onSelect(String template) async {
    String type = FormUtils.recoveryToKey(currentType);

    await post(HttpPreferenceService.updateTemplate(type, template),
        autoHandler: AutoHandler.Toast,
        loadingTip: S.current.loading, onSuccess: (result) {
      switch (templateList.indexOf(currentType)) {
        case 0:
          Config.settingInfo.templates.quotation = template;
          break;
        case 1:
          Config.settingInfo.templates.invoice = template;
          break;
        case 2:
          Config.settingInfo.templates.purchaseOrder = template;
          break;
        case 3:
          Config.settingInfo.templates.delivery = template;
          break;
        case 4:
          Config.settingInfo.templates.creditNote = template;
          break;
      }
      RProvider.myProvider.updateGlobalMap();
      update();
    });
  }

  void onWatch(SettingTemplateEntity value) {
    Routes.navigateTo(RouterGenProviders.templateStyleDetailPage, params: {
      'title': Config.settingData.template
              .firstWhere((element) => element.key == value.template,
                  orElse: () => null)
              ?.name ??
          '',
      'imageUrl': value.imageUrl,
    });
  }

  String getCurrentSelect() {
    switch (templateList.indexOf(currentType)) {
      case 0:
        return Config.settingInfo.templates.quotation;
      case 1:
        return Config.settingInfo.templates.invoice;
      case 2:
        return Config.settingInfo.templates.purchaseOrder;
      case 3:
        return Config.settingInfo.templates.delivery;
      case 4:
        return Config.settingInfo.templates.creditNote;
    }
    return '';
  }
}
